<template>
  <a-card class="confirmation-letter-management-card" title="确认函管理">
    <template #extra>
      <a-space>
        <a-button size="small" @click="refreshData">
          <template #icon>
            <icon-refresh />
          </template>
          刷新
        </a-button>
        <a-button
          size="small"
          @click="showExistingTemplates"
          v-perm="['lindi:tradeApplicationTemplateConfirmLetter:get']"
        >
          <template #icon>
            <icon-folder />
          </template>
          查看已有确认函模板
        </a-button>
        <a-button
          size="small"
          @click="showConfirmationLetterTemplates"
          v-perm="['lindi:tradeApplicationConfirmLetter:add']"
        >
          <template #icon>
            <icon-file />
          </template>
          选择模板生成确认函
        </a-button>
        <a-button
          size="small"
          type="primary"
          @click="showAddModal"
          v-perm="['lindi:tradeApplicationConfirmLetter:add']"
        >
          <template #icon>
            <icon-plus />
          </template>
          添加确认函
        </a-button>
      </a-space>
    </template>

    <!-- 确认函列表 -->
    <div class="confirmation-letter-list">
      <div v-if="props.loading" class="loading-container">
        <a-spin size="large" />
      </div>

      <div v-else-if="tableData.length === 0" class="empty-container">
        <a-empty description="暂无确认函文件" />
      </div>

      <div v-else class="confirmation-letter-grid">
        <div
          v-for="letter in tableData"
          :key="letter.confirmLetterId"
          class="confirmation-letter-item"
        >
          <a-card class="confirmation-letter-card" hoverable>
            <div class="confirmation-letter-header">
              <div class="confirmation-letter-icon">
                <a-avatar :size="48" class="bg-purple-100" shape="square">
                  <icon-file-pdf class="text-purple-600" />
                </a-avatar>
              </div>
              <div class="confirmation-letter-info">
                <div class="confirmation-letter-title">
                  {{ letter.confirmLetterName || "确认函文件" }}
                </div>
                <div class="confirmation-letter-meta">
                  <a-tag :color="getLetterTypeColor(letter.confirmLetterType)">
                    {{ getLetterTypeText(letter.confirmLetterType) }}
                  </a-tag>
                </div>
              </div>
            </div>

            <div class="confirmation-letter-details">
              <div class="detail-row">
                <span class="detail-label">确认函编号：</span>
                <span class="detail-value">{{
                  letter.confirmLetterCode || "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">确认函类型：</span>
                <span class="detail-value">{{
                  getLetterTypeText(letter.confirmLetterType) || "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">签订时间：</span>
                <span class="detail-value">{{
                  formatDateTime(letter.signDate) || "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">创建时间：</span>
                <span class="detail-value">{{
                  formatDateTime(letter.createTime) || "-"
                }}</span>
              </div>
              <div v-if="letter.remark" class="detail-row">
                <span class="detail-label">备注：</span>
                <span class="detail-value">{{ letter.remark }}</span>
              </div>
            </div>

            <div class="confirmation-letter-actions">
              <a-space>
                <a-button size="mini" @click="previewLetter(letter)">
                  <template #icon>
                    <icon-eye />
                  </template>
                  预览
                </a-button>
                <a-button
                  size="mini"
                  type="primary"
                  @click="downloadLetter(letter)"
                >
                  <template #icon>
                    <icon-download />
                  </template>
                  下载
                </a-button>
                <a-button
                  size="mini"
                  @click="editLetter(letter)"
                  v-perm="['lindi:tradeApplicationConfirmLetter:update']"
                >
                  <template #icon>
                    <icon-edit />
                  </template>
                  编辑
                </a-button>
                <a-button
                  size="mini"
                  status="danger"
                  @click="deleteLetter(letter)"
                  v-perm="['lindi:tradeApplicationConfirmLetter:delete']"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  删除
                </a-button>
              </a-space>
            </div>
          </a-card>
        </div>
      </div>
    </div>

    <!-- 添加/编辑确认函弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="700px"
      @cancel="handleModalCancel"
      @ok="handleSubmit"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item field="confirmLetterName" label="确认函名称" required>
          <a-input
            v-model="formData.confirmLetterName"
            placeholder="请输入确认函名称"
          />
        </a-form-item>

        <a-form-item field="confirmLetterCode" label="确认函编号">
          <a-input
            v-model="formData.confirmLetterCode"
            placeholder="请输入确认函编号"
          />
        </a-form-item>

        <a-form-item field="confirmLetterType" label="确认函类型" required>
          <a-select
            v-model="formData.confirmLetterType"
            placeholder="请选择确认函类型"
          >
            <a-option
              v-for="item in dicts[DICT.lindiTradeApplicationConfirmLetter]"
              :key="item.dictKey"
              :value="String(item.dictKey)"
            >
              {{ item.dictValue }}
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="signDate" label="签订时间">
          <a-date-picker
            v-model="formData.signDate"
            style="width: 100%"
            placeholder="请选择签订时间"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>

        <!-- 已有附件展示区域 -->
        <div
          v-if="existingFiles.length > 0"
          class="existing-files-container mb-4"
        >
          <div class="mb-2 flex items-center justify-between">
            <div class="text-gray-500">
              <icon-info-circle class="mr-1" /> 已上传确认函文件
            </div>
          </div>
          <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
            <a-list-item
              v-for="(file, index) in existingFiles"
              :key="file.fileId"
            >
              <a-card class="file-card" hoverable>
                <div class="flex items-start">
                  <div class="file-icon mr-3">
                    <a-avatar :size="40" shape="square">
                      <icon-file-pdf v-if="file.fileType === 'pdf'" />
                      <icon-file-image
                        v-else-if="
                          ['jpg', 'png', 'jpeg'].includes(file.fileType)
                        "
                      />
                      <icon-file v-else />
                    </a-avatar>
                  </div>
                  <div class="flex-1 overflow-hidden">
                    <div class="font-medium truncate mb-1">
                      {{ file.fileName }}
                    </div>
                    <div class="text-gray-500 text-xs mb-1">
                      上传时间：{{ formatDateTime(file.uploadTime) || "未知" }}
                    </div>
                    <div class="mt-2">
                      <a-space>
                        <a-button
                          size="mini"
                          type="primary"
                          @click="downloadFile(file)"
                        >
                          <template #icon> </template>
                          下载
                        </a-button>
                        <a-button size="mini" @click="previewFile(file)">
                          <template #icon> </template>
                          预览
                        </a-button>
                        <a-button
                          size="mini"
                          status="danger"
                          @click="removeExistingFile(index)"
                        >
                          <template #icon> </template>
                          删除
                        </a-button>
                      </a-space>
                    </div>
                  </div>
                </div>
              </a-card>
            </a-list-item>
          </a-list>
        </div>

        <a-form-item field="confirmLetterFile" label="确认函文件">
          <uploadFile
            ref="confirmLetterUploadFileRef"
            :fileSource="fs"
            :limit="1"
            accept=".pdf,.doc,.docx"
            @uploadSuccess="handleUploadSuccess"
          >
            <template #upload-button>
              <div class="upload-area">
                <icon-upload />
                <div class="upload-text">点击上传确认函文件</div>
                <div class="upload-tip">
                  支持 PDF、DOC、DOCX 格式，文件大小不超过 10MB
                </div>
              </div>
            </template>
          </uploadFile>
        </a-form-item>

        <a-form-item field="remark" label="备注">
          <a-textarea
            v-model="formData.remark"
            placeholder="请输入备注信息"
            :auto-size="{ minRows: 3, maxRows: 6 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 确认函模板列表弹窗 -->
    <a-modal
      v-model:visible="templateListVisible"
      title="选择模板生成确认函"
      width="800px"
      :footer="false"
    >
      <div v-if="confirmationLetterTemplatesLoading" class="text-center py-8">
        <a-spin size="large" />
        <div class="mt-2 text-gray-500">加载中...</div>
      </div>

      <div
        v-else-if="confirmationLetterTemplates.length === 0"
        class="text-center py-8"
      >
        <div class="text-gray-500">暂无确认函模板</div>
      </div>

      <div v-else>
        <!-- 模板选择器 -->
        <a-form-item label="选择模板" class="mb-4">
          <a-select
            v-model="selectedTemplate"
            placeholder="请选择确认函模板"
            size="large"
            :loading="confirmationLetterTemplatesLoading"
            @change="onTemplateChange"
          >
            <a-option
              v-for="template in confirmationLetterTemplates"
              :key="template.contractTemplateId"
              :value="template"
            >
              {{ template.contractTemplateName }}
            </a-option>
          </a-select>
        </a-form-item>

        <!-- 确认函类型选择器 -->
        <a-form-item label="确认函类型" class="mb-4">
          <a-select
            v-model="selectedConfirmationLetterType"
            placeholder="请选择确认函类型"
            size="large"
          >
            <a-option
              v-for="item in dicts[DICT.lindiTradeApplicationConfirmLetter]"
              :key="item.dictKey"
              :value="String(item.dictKey)"
            >
              {{ item.dictValue }}
            </a-option>
          </a-select>
        </a-form-item>

        <!-- 确认函模板信息展示 -->
        <div v-if="selectedTemplate" class="template-info-section">
          <a-divider>模板信息</a-divider>
          <a-card class="template-info-card" :bordered="false">
            <div class="template-header">
              <div class="template-icon">
                <a-avatar :size="48" shape="square" class="bg-purple-100">
                  <icon-file-pdf class="text-purple-600" />
                </a-avatar>
              </div>
              <div class="template-basic-info">
                <div class="template-name">
                  {{ selectedTemplate.contractTemplateName }}
                </div>
                <div class="template-meta">
                  <a-tag color="blue" size="small">
                    {{
                      dicts[proxy.DICT.lindiContractTemplateType][
                        selectedTemplate.contractTemplateType
                      ]["dictValue"] || "标准模板"
                    }}
                  </a-tag>
                </div>
              </div>
            </div>

            <a-descriptions
              :column="2"
              size="small"
              class="template-descriptions"
            >
              <a-descriptions-item label="文件名称">
                {{ selectedTemplate.contractTemplateFile?.fileName || "-" }}
              </a-descriptions-item>
              <a-descriptions-item label="文件大小">
                {{
                  formatFileSize(
                    selectedTemplate.contractTemplateFile?.fileSize
                  )
                }}
              </a-descriptions-item>
              <a-descriptions-item label="文件类型">
                {{
                  selectedTemplate.contractTemplateFile?.fileType?.toUpperCase()
                }}
              </a-descriptions-item>
              <a-descriptions-item label="创建时间">
                {{
                  formatDateTime(
                    selectedTemplate.contractTemplateFile?.createTime
                  )
                }}
              </a-descriptions-item>
              <a-descriptions-item label="模板状态">
                <a-tag
                  :color="getStatusColor(selectedTemplate.status)"
                  size="small"
                >
                  {{ getStatusText(selectedTemplate.status) }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="备注">
                {{ selectedTemplate.remark || "-" }}
              </a-descriptions-item>
            </a-descriptions>

            <div
              class="template-actions"
              v-if="selectedTemplate.confirmationLetterTemplateFile"
            >
              <a-space>
                <a-button
                  size="small"
                  @click="previewTemplate(selectedTemplate)"
                >
                  <template #icon><icon-eye /></template>
                  预览模板
                </a-button>
                <a-button
                  size="small"
                  type="outline"
                  @click="downloadTemplate(selectedTemplate)"
                >
                  下载模板
                </a-button>
                <a-button
                  size="small"
                  status="danger"
                  @click="deleteTemplate(selectedTemplate)"
                >
                  <template #icon><icon-delete /></template>
                  删除模板
                </a-button>
              </a-space>
            </div>
          </a-card>
        </div>

        <!-- 生成确认函按钮 -->
        <div class="mt-4" v-if="selectedTemplate">
          <a-button
            type="primary"
            size="large"
            @click="generateConfirmationLetter"
            :loading="generateConfirmationLetterLoading"
            class="w-full"
          >
            <template #icon><icon-file /></template>
            生成确认函
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 查看已有确认函模板弹窗 -->
    <a-modal
      v-model:visible="existingTemplatesVisible"
      title="已有确认函模板"
      width="1000px"
      :footer="false"
    >
      <div v-if="existingTemplatesLoading" class="loading-container">
        <a-spin size="large" />
        <div class="mt-2 text-gray-500">加载中...</div>
      </div>

      <div
        v-else-if="existingTemplatesList.length === 0"
        class="empty-container"
      >
        <a-empty description="暂无确认函模板" />
      </div>

      <div v-else class="confirmation-letter-grid">
        <div
          v-for="template in existingTemplatesList"
          :key="template.tradeApplicationTemplateConfirmLetterId"
          class="confirmation-letter-item"
        >
          <a-card class="confirmation-letter-card" hoverable>
            <div class="confirmation-letter-header">
              <div class="confirmation-letter-icon">
                <a-avatar :size="48" class="bg-green-100" shape="square">
                  <icon-file-pdf class="text-green-600" />
                </a-avatar>
              </div>
              <div class="confirmation-letter-info">
                <div class="confirmation-letter-title">
                  {{
                    template.confirmationLetterTemplate?.fileName ||
                    template.file?.fileName ||
                    "确认函模板"
                  }}
                </div>
                <div class="confirmation-letter-meta">
                  <span class="confirmation-letter-type">{{
                    getLetterTypeText(template.letterType) || "标准模板"
                  }}</span>
                </div>
              </div>
            </div>

            <div class="confirmation-letter-details">
              <div class="detail-row">
                <span class="detail-label">文件名称：</span>
                <span class="detail-value">{{
                  template.confirmationLetterTemplate?.fileName ||
                  template.file?.fileName ||
                  "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">文件大小：</span>
                <span class="detail-value">{{
                  formatFileSize(
                    template.confirmationLetterTemplate?.fileSize ||
                      template.file?.fileSize
                  )
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">文件类型：</span>
                <span class="detail-value">{{
                  (
                    template.confirmationLetterTemplate?.fileType ||
                    template.file?.fileType
                  )?.toUpperCase() || "-"
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">创建时间：</span>
                <span class="detail-value">{{
                  formatDateTime(template.createTime)
                }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">更新时间：</span>
                <span class="detail-value">{{
                  formatDateTime(template.updateTime)
                }}</span>
              </div>
              <div
                v-if="
                  template.confirmationLetterTemplate?.remark ||
                  template.file?.remark
                "
                class="detail-row"
              >
                <span class="detail-label">备注：</span>
                <span class="detail-value">{{
                  template.confirmationLetterTemplate?.remark ||
                  template.file?.remark
                }}</span>
              </div>
            </div>

            <div class="confirmation-letter-actions">
              <a-space>
                <a-button
                  size="mini"
                  @click="previewExistingTemplate(template)"
                >
                  <template #icon>
                    <icon-eye />
                  </template>
                  预览
                </a-button>
                <a-button
                  size="mini"
                  type="primary"
                  @click="downloadExistingTemplate(template)"
                >
                  <template #icon>
                    <icon-download />
                  </template>
                  下载
                </a-button>
                <a-button
                  size="mini"
                  status="danger"
                  @click="deleteExistingTemplate(template)"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  删除
                </a-button>
              </a-space>
            </div>
          </a-card>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref, watch } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconRefresh,
  IconPlus,
  IconEye,
  IconDownload,
  IconEdit,
  IconCheck,
  IconDelete,
  IconFilePdf,
  IconUpload,
  IconFile,
  IconFolder,
  IconInfoCircle,
  IconFileImage,
} from "@arco-design/web-vue/es/icon";
import uploadFile from "~/components/uploadFile/index.vue";
import { fileSource } from "~/utils/sys.js";
import {
  getTradeApplicationConfirmLetterListByTradeApplicationIdApi,
  addTradeApplicationConfirmLetterApi,
  updateTradeApplicationConfirmLetterByConfirmLetterIdApi,
  deleteTradeApplicationConfirmLetterByConfirmLetterIdApi,
} from "~/api/lindi/tradeApplicationConfirmLetter.js";
import {
  getPageTradeApplicationTemplateConfirmLetterListApi,
  generateTemplateConfirmLetterApi,
  deleteTradeApplicationTemplateConfirmLetterByTemplateConfirmLetterIdApi,
  getContractTemplateListApi,
} from "~/api/lindi/tradeApplicationTemplateConfirmLetter.js";
import { deleteFileApi } from "~/api/basic/file.js";
import { DICT } from "~/utils/dict.js";

// 定义props
const props = defineProps({
  tradeApplicationId: {
    type: String,
    required: true,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

// 定义emits
const emit = defineEmits([]);

// 全局实例
const { proxy } = getCurrentInstance();

// 加载字典
const dicts = proxy.LoadDicts([
  DICT.lindiTradeApplicationConfirmLetter,
  DICT.commonNumberStatus,
  DICT.lindiTradeApplicationTemplateConfirmLetter,
  DICT.lindiContractTemplateType,
]);

// 响应式数据
const modalVisible = ref(false);
const modalTitle = ref("添加确认函");
const formRef = ref(null);
const confirmLetterUploadFileRef = ref(null);
const tableData = ref([]);
const editingLetter = ref(null);
const existingFiles = ref([]);
const newUploadedFileIds = ref([]); // 跟踪新上传的文件ID，用于取消时清理
const submitLoading = ref(false); // 提交加载状态

// 文件来源配置
const fs =
  fileSource.lindi_trade_confirm_file?.key ||
  "lindi_trade_application_confirm_letter_file";

// 模板相关数据
const templateListVisible = ref(false);
const existingTemplatesVisible = ref(false);
const confirmationLetterTemplates = ref([]);
const confirmationLetterTemplatesLoading = ref(false);
const contractTemplates = ref([]); // 合同模板列表
const contractTemplatesLoading = ref(false); // 合同模板加载状态
const existingTemplatesList = ref([]);
const existingTemplatesLoading = ref(false);
const selectedTemplate = ref(null);
const selectedConfirmationLetterType = ref("");
const generateConfirmationLetterLoading = ref(false);

// 表单数据
const formData = reactive({
  confirmLetterId: null,
  tradeApplicationId: null,
  confirmLetterName: "",
  confirmLetterCode: "",
  confirmLetterType: "",
  signDate: "",
  fileId: null,
  remark: "",
});

// 表单验证规则
const formRules = {
  confirmLetterName: [{ required: true, message: "请输入确认函名称" }],
  confirmLetterType: [{ required: true, message: "请选择确认函类型" }],
};

// 获取确认函类型文本
const getLetterTypeText = (type) => {
  const dict = dicts[DICT.lindiTradeApplicationConfirmLetter];
  if (dict && dict.length > 0) {
    const item = dict.find((d) => String(d.dictKey) === String(type));
    return item ? item.dictValue : "未知类型";
  }
  return "未知类型";
};

// 获取确认函类型颜色
const getLetterTypeColor = (type) => {
  const dict = dicts[DICT.lindiTradeApplicationConfirmLetter];
  if (dict && dict.length > 0) {
    const item = dict.find((d) => String(d.dictKey) === String(type));
    return item?.dictClass || "blue";
  }
  return "blue";
};

// 获取状态文本
const getStatusText = (status) => {
  const dict = dicts[DICT.commonNumberStatus];
  if (dict && dict.length > 0) {
    const item = dict.find((d) => String(d.dictKey) === String(status));
    return item ? item.dictValue : "未知状态";
  }
  return "未知状态";
};

// 获取状态颜色
const getStatusColor = (status) => {
  const dict = dicts[DICT.commonNumberStatus];
  if (dict && dict.length > 0) {
    const item = dict.find((d) => String(d.dictKey) === String(status));
    return item?.dictClass || "gray";
  }
  return "gray";
};

// 刷新数据
const refreshData = () => {
  loadConfirmationLetters();
};

// 显示添加弹窗
const showAddModal = () => {
  modalTitle.value = "添加确认函";
  editingLetter.value = null;
  newUploadedFileIds.value = []; // 清空文件跟踪
  resetForm();
  modalVisible.value = true;
};

// 加载确认函列表
const loadConfirmationLetters = () => {
  if (!props.tradeApplicationId) {
    return;
  }

  getTradeApplicationConfirmLetterListByTradeApplicationIdApi(
    props.tradeApplicationId
  )
    .then((res) => {
      tableData.value = res || [];
      console.log("tableData.value", tableData.value);
    })
    .catch((error) => {
      console.error("获取确认函信息失败:", error);
      Message.error("获取确认函信息失败");
      tableData.value = [];
    });
};

// 预览确认函
const previewLetter = (letter) => {
  if (letter.file?.fileUrl) {
    window.open(letter.file.fileUrl, "_blank");
  } else {
    Message.warning("该确认函暂无文件可预览");
  }
};

// 下载确认函
const downloadLetter = (letter) => {
  if (letter.file?.fileUrl) {
    const link = document.createElement("a");
    link.href = letter.file.fileUrl;
    link.download = letter.file.fileName || `${letter.confirmLetterName}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning("该确认函暂无文件可下载");
  }
};

// 编辑确认函
const editLetter = (letter) => {
  modalTitle.value = "编辑确认函";
  editingLetter.value = letter;
  newUploadedFileIds.value = [];

  // 填充表单数据
  Object.assign(formData, {
    confirmLetterId: letter.confirmLetterId,
    tradeApplicationId: letter.tradeApplicationId,
    confirmLetterName: letter.confirmLetterName || "",
    confirmLetterCode: letter.confirmLetterCode || "",
    confirmLetterType: String(letter.confirmLetterType || ""),
    signDate: letter.signDate || "",
    fileId: letter.fileId || null,
    remark: letter.remark || "",
  });

  // 设置已有文件
  if (letter.file) {
    existingFiles.value = [
      {
        fileId: letter.file.fileId,
        fileName: letter.file.fileName,
        fileUrl: letter.file.fileUrl,
        uploadTime: letter.file.createTime,
      },
    ];
  } else {
    existingFiles.value = [];
  }

  modalVisible.value = true;
};

// 验证确认函（模拟操作）
const verifyLetter = (letter) => {
  Modal.confirm({
    title: "确认验证",
    content: `确定要验证确认函"${letter.letterTitle}"吗？`,
    onOk: () => {
      // 模拟验证操作
      const index = tableData.value.findIndex(
        (item) => item.confirmationLetterId === letter.confirmationLetterId
      );
      if (index !== -1) {
        tableData.value[index].status = "verified";
      }
      Message.success("确认函验证成功（模拟）");
    },
  });
};

// 删除确认函
const deleteLetter = (letter) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除确认函"${letter.confirmLetterName}"吗？此操作不可恢复。`,
    onOk: () => {
      deleteTradeApplicationConfirmLetterByConfirmLetterIdApi(
        letter.confirmLetterId
      )
        .then(() => {
          Message.success("删除成功");
          // 刷新列表
          loadConfirmationLetters();
        })
        .catch((error) => {
          console.error("删除确认函失败:", error);
          Message.error("删除失败，请重试");
        });
    },
  });
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "-";
  try {
    const date = new Date(dateTime);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  } catch (error) {
    return dateTime;
  }
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return "-";
  const units = ["B", "KB", "MB", "GB"];
  let index = 0;
  let fileSize = size;

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }

  return `${fileSize.toFixed(1)} ${units[index]}`;
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      return false;
    }

    submitLoading.value = true;

    // 准备提交数据
    const submitData = {
      ...formData,
      tradeApplicationId: props.tradeApplicationId,
    };

    // 处理签订时间格式
    if (submitData.signDate) {
      if (typeof submitData.signDate === "object") {
        const date = new Date(submitData.signDate);
        if (!isNaN(date.getTime())) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0");
          const day = String(date.getDate()).padStart(2, "0");
          const hours = String(date.getHours()).padStart(2, "0");
          const minutes = String(date.getMinutes()).padStart(2, "0");
          const seconds = String(date.getSeconds()).padStart(2, "0");
          submitData.signDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
      } else if (
        typeof submitData.signDate === "string" &&
        submitData.signDate.length === 10
      ) {
        submitData.signDate = submitData.signDate + " 00:00:00";
      }
    }

    // 处理文件上传
    if (
      confirmLetterUploadFileRef.value &&
      confirmLetterUploadFileRef.value.fileList &&
      confirmLetterUploadFileRef.value.fileList.length > 0
    ) {
      const file = confirmLetterUploadFileRef.value.fileList[0];
      if (file && file.response && file.response.fileId) {
        submitData.fileId = file.response.fileId;
      } else if (file && file.uid && existingFiles.value.length > 0) {
        submitData.fileId = existingFiles.value[0].fileId;
      }
    } else {
      if (existingFiles.value.length > 0) {
        submitData.fileId = existingFiles.value[0].fileId;
      }
    }

    // 如果仍然没有获取到文件ID，尝试使用getUploadFileId方法
    if (!submitData.fileId && confirmLetterUploadFileRef.value) {
      const uploadFileIds = confirmLetterUploadFileRef.value.getUploadFileId();
      if (uploadFileIds) {
        const fileIdArray = uploadFileIds.split(",").filter(Boolean);
        if (fileIdArray.length > 0) {
          submitData.fileId = fileIdArray[0];
        }
      }
    }

    console.log("submitData", submitData);

    // 执行提交操作
    const submitPromise = editingLetter.value
      ? updateTradeApplicationConfirmLetterByConfirmLetterIdApi({
          confirmLetterId: editingLetter.value.confirmLetterId,
          ...submitData,
        })
      : addTradeApplicationConfirmLetterApi(submitData);

    submitPromise
      .then((response) => {
        if (response.code === 200) {
          Message.success(
            editingLetter.value ? "确认函更新成功" : "确认函添加成功"
          );
          newUploadedFileIds.value = [];
          modalVisible.value = false;
          resetForm();
          loadConfirmationLetters();
        } else {
          Message.error(response.message || "操作失败，请重试");
        }
      })
      .catch((error) => {
        console.error("提交失败:", error);
        Message.error("操作失败，请重试");
      })
      .finally(() => {
        submitLoading.value = false;
      });
  });
};

// 弹窗取消处理
const handleModalCancel = () => {
  // 清理新上传的文件
  if (newUploadedFileIds.value.length > 0 && !editingLetter.value) {
    newUploadedFileIds.value.forEach((fileId) => {
      deleteFileApi(fileId)
        .then(() => {
          console.log("清理文件成功:", fileId);
        })
        .catch((error) => {
          console.error("清理文件失败:", fileId, error);
        });
    });
    newUploadedFileIds.value = [];
  }

  modalVisible.value = false;
  resetForm();
};

// 文件上传成功处理
const handleUploadSuccess = (response, fileItem, fileList) => {
  console.log("文件上传成功:", response);
  if (response && response.fileId) {
    // 在新增模式下，跟踪新上传的文件ID
    if (!editingLetter.value) {
      newUploadedFileIds.value.push(response.fileId);
    }
    Message.success("文件上传成功");
  }
};

// 文件移除处理
const handleFileRemove = (fileItem) => {
  return new Promise((resolve, reject) => {
    try {
      // 如果是新上传的文件，从跟踪列表中移除
      if (fileItem.response && fileItem.response.fileId) {
        const index = newUploadedFileIds.value.indexOf(
          fileItem.response.fileId
        );
        if (index > -1) {
          newUploadedFileIds.value.splice(index, 1);
        }
      }

      // 如果是已存在的文件，从已存在文件列表中移除
      if (fileItem.fileId) {
        const index = existingFiles.value.findIndex(
          (file) => file.fileId === fileItem.fileId
        );
        if (index > -1) {
          existingFiles.value.splice(index, 1);
        }
      }

      resolve(true);
    } catch (error) {
      console.error("移除文件失败:", error);
      Message.error("移除文件失败");
      reject(false);
    }
  });
};

// 清理未使用的文件
const cleanupUnusedFiles = () => {
  if (newUploadedFileIds.value.length > 0) {
    const deletePromises = newUploadedFileIds.value.map((fileId) => {
      return deleteFileApi(fileId);
    });

    Promise.all(deletePromises)
      .then(() => {
        newUploadedFileIds.value = [];
      })
      .catch((error) => {
        console.error("清理未使用文件失败:", error);
      });
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    confirmLetterId: null,
    tradeApplicationId: null,
    confirmLetterName: "",
    confirmLetterCode: "",
    confirmLetterType: "",
    signDate: "",
    fileId: null,
    remark: "",
  });
  existingFiles.value = [];
  editingLetter.value = null;

  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 清空上传组件的文件列表
  if (
    confirmLetterUploadFileRef.value &&
    confirmLetterUploadFileRef.value.fileList !== undefined
  ) {
    confirmLetterUploadFileRef.value.fileList = [];
  }
};

// 移除已有文件
const removeExistingFile = (index) => {
  existingFiles.value.splice(index, 1);
};

// 下载文件
const downloadFile = (file) => {
  if (file.fileUrl) {
    const link = document.createElement("a");
    link.href = file.fileUrl;
    link.download = file.fileName;
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    Message.success("开始下载文件");
  }
};

// 预览文件
const previewFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  }
};

// 显示确认函模板列表
const showConfirmationLetterTemplates = () => {
  // 先显示弹窗
  templateListVisible.value = true;

  // 再加载数据
  confirmationLetterTemplatesLoading.value = true;

  getContractTemplateListApi()
    .then((res) => {
      confirmationLetterTemplates.value = res || [];
      if (confirmationLetterTemplates.value.length > 0) {
        selectedTemplate.value = confirmationLetterTemplates.value[0];
      } else {
        Message.info("暂无合同模板");
      }
    })
    .catch((error) => {
      console.error("获取合同模板失败:", error);
      Message.error("获取合同模板失败");
    })
    .finally(() => {
      confirmationLetterTemplatesLoading.value = false;
    });
};

// 显示已有确认函模板
const showExistingTemplates = () => {
  existingTemplatesVisible.value = true;
  existingTemplatesLoading.value = true;

  getPageTradeApplicationTemplateConfirmLetterListApi({
    pageNum: 1,
    pageSize: 100,
    tradeApplicationId: props.tradeApplicationId,
  })
    .then((response) => {
      existingTemplatesList.value = response.records || [];
    })
    .catch((error) => {
      console.error("加载已有确认函模板失败:", error);
      Message.error("加载已有确认函模板失败");
      existingTemplatesList.value = [];
    })
    .finally(() => {
      existingTemplatesLoading.value = false;
    });
};

// 模板选择变化
const onTemplateChange = (template) => {
  selectedTemplate.value = template;
  // 根据模板类型自动设置确认函类型
  if (template && template.confirmationLetterTemplateType) {
    selectedConfirmationLetterType.value =
      template.confirmationLetterTemplateType;
  }
};

// 预览模板
const previewTemplate = (template) => {
  if (template.fileId) {
    previewFileApi(template.fileId)
      .then((response) => {
        if (response && response.url) {
          window.open(response.url, "_blank");
        } else {
          Message.warning("无法获取预览链接");
        }
      })
      .catch((error) => {
        console.error("预览模板失败:", error);
        Message.error("预览失败，请重试");
      });
  } else {
    Message.warning("暂无可预览的文件");
  }
};

// 下载模板
const downloadTemplate = (template) => {
  if (template.fileId) {
    downloadFileApi(template.fileId)
      .then((response) => {
        if (response && response.url) {
          const link = document.createElement("a");
          link.href = response.url;
          link.download =
            template.confirmationLetterTemplateName || "确认函模板";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          Message.success("下载成功");
        } else {
          Message.warning("无法获取下载链接");
        }
      })
      .catch((error) => {
        console.error("下载模板失败:", error);
        Message.error("下载失败，请重试");
      });
  } else {
    Message.warning("暂无可下载的文件");
  }
};

// 删除模板
const deleteTemplate = (template) => {
  // 模拟删除操作
  new Promise((resolve) => setTimeout(resolve, 500))
    .then(() => {
      // 从列表中移除
      const index = confirmationLetterTemplates.value.findIndex(
        (t) =>
          t.confirmationLetterTemplateId ===
          template.confirmationLetterTemplateId
      );
      if (index > -1) {
        confirmationLetterTemplates.value.splice(index, 1);
      }

      // 如果删除的是当前选中的模板，清空选择
      if (
        selectedTemplate.value?.confirmationLetterTemplateId ===
        template.confirmationLetterTemplateId
      ) {
        selectedTemplate.value = null;
        selectedConfirmationLetterType.value = "";
      }

      Message.success("模板删除成功（模拟）");
    })
    .catch((error) => {
      console.error("删除模板失败:", error);
      Message.error("删除模板失败");
    });
};

// 生成确认函
const generateConfirmationLetter = () => {
  if (!selectedTemplate.value) {
    Message.warning("请选择确认函模板");
    return;
  }

  if (!selectedConfirmationLetterType.value) {
    Message.warning("请选择确认函类型");
    return;
  }

  generateConfirmationLetterLoading.value = true;

  generateTemplateConfirmLetterApi({
    tradeApplicationId: props.tradeApplicationId,
    templateId: selectedTemplate.value.confirmationLetterTemplateId,
    confirmLetterType: selectedConfirmationLetterType.value,
  })
    .then((response) => {
      Message.success("确认函生成成功");
      templateListVisible.value = false;
      selectedTemplate.value = null;
      selectedConfirmationLetterType.value = "";
      loadConfirmationLetters();
    })
    .catch((error) => {
      console.error("生成确认函失败:", error);
      Message.error("生成失败，请重试");
    })
    .finally(() => {
      generateConfirmationLetterLoading.value = false;
    });
};

// 预览已有模板
const previewExistingTemplate = (template) => {
  if (template.file?.fileUrl) {
    window.open(template.file.fileUrl, "_blank");
  } else {
    Message.warning("暂无可预览的文件");
  }
};

// 下载已有模板
const downloadExistingTemplate = (template) => {
  if (template.file?.fileUrl) {
    const link = document.createElement("a");
    link.href = template.file.fileUrl;
    link.download =
      template.confirmationLetterTemplate?.fileName ||
      template.file?.fileName ||
      "确认函模板";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning("暂无可下载的文件");
  }
};

// 删除已有模板
const deleteExistingTemplate = (template) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除模板"${
      template.confirmationLetterTemplate?.fileName || template.file?.fileName
    }"吗？此操作不可恢复。`,
    onOk: () => {
      deleteTradeApplicationTemplateConfirmLetterByTemplateConfirmLetterIdApi(
        template.templateConfirmLetterId
      )
        .then((response) => {
          if (response.code === 200) {
            Message.success("模板删除成功");
            showExistingTemplates(); // 重新加载列表
          } else {
            Message.error(response.message || "删除失败，请重试");
          }
        })
        .catch((error) => {
          console.error("删除已有模板失败:", error);
          Message.error("删除失败，请重试");
        });
    },
  });
};

// 监听tradeApplicationId变化
watch(
  () => props.tradeApplicationId,
  (newId) => {
    if (newId) {
      loadConfirmationLetters();
    }
  },
  { immediate: true }
);

// 组件挂载时加载数据
onMounted(() => {
  loadConfirmationLetters();
});
</script>

<style scoped>
.confirmation-letter-management-card {
  margin-bottom: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.confirmation-letter-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.confirmation-letter-item {
  height: fit-content;
}

.confirmation-letter-card {
  height: 100%;
  transition: all 0.3s ease;
}

.confirmation-letter-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.confirmation-letter-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.confirmation-letter-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.confirmation-letter-info {
  flex: 1;
  min-width: 0;
}

.confirmation-letter-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 4px;
  word-break: break-word;
}

.confirmation-letter-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.confirmation-letter-type {
  font-size: 12px;
  color: #86909c;
  background: #f2f3f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.confirmation-letter-type-tag {
  min-width: 80px;
  text-align: center;
}

.confirmation-letter-details {
  margin-bottom: 16px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-label {
  color: #86909c;
  width: 120px;
  flex-shrink: 0;
}

.detail-value {
  color: #1d2129;
  flex: 1;
  word-break: break-word;
}

.confirmation-letter-actions {
  border-top: 1px solid #f2f3f5;
  padding-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.upload-text {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}

.upload-tip {
  margin-top: 4px;
  color: #999;
  font-size: 12px;
}

.bg-purple-100 {
  background-color: #f3e8ff;
}

.text-purple-600 {
  color: #9333ea;
}

.bg-green-100 {
  background-color: #dcfce7;
}

.text-green-600 {
  color: #16a34a;
}

/* 模板相关样式 */
.template-info-section {
  margin-top: 16px;
}

.template-info-card {
  background: #fafafa;
  border-radius: 8px;
}

.template-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.template-icon {
  margin-right: 12px;
}

.template-basic-info {
  flex: 1;
}

.template-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.template-meta {
  display: flex;
  align-items: center;
}

.template-descriptions {
  margin-bottom: 16px;
}

.template-actions {
  padding-top: 12px;
  border-top: 1px solid #e5e5e5;
}

@media (max-width: 768px) {
  .confirmation-letter-grid {
    grid-template-columns: 1fr;
  }

  .template-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .template-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }
}
</style>
